package rabbitmq.topic;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import rabbitmq.contant.Contants;

/**
 * 通配符模式生产者
 */
public class Producer {
    public static void main(String[] args) throws Exception {
        // 1.建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Contants.HOST);
        connectionFactory.setPort(Contants.PORT);
        connectionFactory.setUsername(Contants.USER_NAME);
        connectionFactory.setPassword(Contants.PASSWORD);
        connectionFactory.setVirtualHost(Contants.VIRTUAL_HOST);
        Connection connection = connectionFactory.newConnection();

        // 2.开启信道
        Channel channel = connection.createChannel();
        // 3.声明交换机
        channel.exchangeDeclare(Contants.TOPIC_EXCHANGE, BuiltinExchangeType.TOPIC,true);
        // 4.声明队列
        channel.queueDeclare(Contants.TOPIC_QUEUE1,true,false,false,null);
        channel.queueDeclare(Contants.TOPIC_QUEUE2,true,false,false,null);
        // 5.交换机和队列绑定
        channel.queueBind(Contants.TOPIC_QUEUE1,Contants.TOPIC_EXCHANGE,"*.a.*",null);
        channel.queueBind(Contants.TOPIC_QUEUE2,Contants.TOPIC_EXCHANGE,"*.*.b",null);
        channel.queueBind(Contants.TOPIC_QUEUE2,Contants.TOPIC_EXCHANGE,"c.#",null);
        // 6.发送消息
        String msg_a = "hello topic,my routingkey is ae.a.f";
        channel.basicPublish(Contants.TOPIC_EXCHANGE,"ae.a.f",null,msg_a.getBytes()); // 转发的Q1

        String msg_b = "hello topic,my routingkey is ef.a.b";
        channel.basicPublish(Contants.TOPIC_EXCHANGE,"ef.a.b",null,msg_b.getBytes()); // 转发到Q1和Q2

        String msg_c = "hello topic,my routingkey is c.ef.d";
        channel.basicPublish(Contants.TOPIC_EXCHANGE,"c.ef.d",null,msg_c.getBytes()); // 转发到Q2

        System.out.println("消息发送成功");
        // 7.释放资源
        channel.close();
        connection.close();
    }
}
